package cn.tk.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Nonnull;

/**
 * Created by denglw on 2017-08-11.<br>
 * Desc: beanFactory增强，提供获取beanFactory中管理bean的常用方法
 */
@Component
public final class BeanCreater implements BeanFactoryPostProcessor {
    /**
     * Spring应用上下文环境
     */
    private static ConfigurableListableBeanFactory beanFactory;

    private BeanCreater() {}

    @Override
    public void postProcessBeanFactory(@Nonnull ConfigurableListableBeanFactory beanFactory)
            throws BeansException {
        BeanCreater.beanFactory = beanFactory;
    }

    /**
     * 获取类型为requiredType的对象<br/>
     * @param clazz 对象类型
     * @return T bean的实例
     * @throws BeansException 失败
     */
    public static <T> T getBean(Class<T> clazz) throws BeansException {
    	return beanFactory != null ? beanFactory.getBean(clazz) : null;
    }

    /**
     * beanFactory中是否包含给定名称的bean定义<br/>
     * @param name bean名称
     * @return boolean 包含时返回true
     */
    public static boolean containsBean(String name) {
        return beanFactory.containsBean(name);
    }

    /**
     * 判断以给定名字注册的bean定义是singleton还是prototype；<br/>
     * 如果与给定名字相应的bean定义没有被找到，将会抛出一个异常<br/>
     * @param name bean名称
     * @return boolean 单例时返回true
     * @throws NoSuchBeanDefinitionException 失败
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
        return beanFactory.isSingleton(name);
    }

    /**
     * 获取给定名称bean的Class类型<br/>
     * @param name bean名称
     * @return Class 注册对象的类型
     * @throws NoSuchBeanDefinitionException 没有指定名称的bean
     */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
        return beanFactory.getType(name);
    }

    /**
     * 获取指定名称bean的别名数组<br/>
     * @param name bean名称
     * @return String[] bean的别名数组
     * @throws NoSuchBeanDefinitionException 没有指定名称的bean
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
        return beanFactory.getAliases(name);
    }

}
